package com.sgb.merchant.view.activity

import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bumptech.glide.Glide
import com.sgb.link.entity.EventConstant
import com.sgb.link.entity.MainEvent
import com.sgb.link.entity.merchant.DemandDetailEntity
import com.sgb.link.entity.merchant.DemandInfoEntity
import com.sgb.link.entity.merchant.DemandType
import com.sgb.link.router.PathMerchant
import com.sgb.merchant.R
import com.sgb.merchant.databinding.MerchantActivityPublishDemandBinding
import com.sgb.merchant.viewmodel.PublishDemandModel

import com.swgk.core.base.model.entity.RouterKey
import com.swgk.core.common.base.BaseActivity

import com.swgk.core.customview.ItemInputTextView
import com.swgk.core.dialog.DialogHelper
import com.swgk.core.dialog.RoundDialog
import com.swgk.core.recyclerview.entity.BaseAreaEntity
import com.swgk.core.util.*
import com.yalantis.ucrop.util.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.Serializable
import java.util.*


/**
 * @author: 王彬臣
 * @date: 2021/9/17
 * @Description: 发布投资需求
 */
@Route(path = PathMerchant.PublishDemandActivity)
class PublishDemandActivity :
    BaseActivity<PublishDemandModel, MerchantActivityPublishDemandBinding>(),
    ItemInputTextView.OnWholeItemClickListener {
    @JvmField
    @Autowired(name = RouterKey.NO, desc = "详情no")
    var no:String=""
    @JvmField
    @Autowired(name = RouterKey.BOOLEAN2,desc="是否来着我的页面")
    var isSelf=false

    var isPublish=true
    var hasContent = false
    var filePath = ""
    var fileSize = ""
    var fileType = ""
    var fileName = ""
    lateinit var strTitle: String
    lateinit var strType: String
    lateinit var strMoney: String
    lateinit var strArea: String
    lateinit var strLinkName: String
    lateinit var strLinkPhone: String
    lateinit var strDesc: String
    var map = mutableMapOf<String, Any?>()
    var cityList = mutableListOf<BaseAreaEntity<*>>()
    var mType = mutableListOf<DemandType>()
    var mData: DemandDetailEntity? = null


    //类型选择器
    lateinit var mTypePicker: OptionsPickerView<*>
    private val FILE_TYPE_RAR = ".rar"
    private val FILE_TYPE_ZIP = ".zip"
    private val FILE_TYPE_DOC = ".doc"
    private val FILE_TYPE_DOCX = ".docx"
    private val FILE_TYPE_PPT = ".ppt"
    private val FILE_TYPE_PPTX = ".pptx"
    private val FILE_TYPE_XLS = ".xls"
    private val FILE_TYPE_XLSX = ".xlsx"
    private val FILE_TYPE_PDF = ".pdf"
    private val FILE_TYPE_JPG = ".jpg"
    private val FILE_TYPE_PNG = ".png"
    private val FILE_TYPE_JPEG = ".jpeg"
    companion object {
        // 打开文件管理器
        const val OPEN_FILE = 102
        const val SELECT_CITY = 1000
    }

    override fun layoutId(): Int {
        return R.layout.merchant_activity_publish_demand
    }

    override fun createViewModel() {
        mViewModel = ViewModelProvider(this).get(PublishDemandModel::class.java)

    }

    override fun init() {
        ARouter.getInstance().inject(this)
        mBinding.includeTitle.titleView.text = "投资需求"
        mBinding.includeTitle.ivBack.setOnClickListener {
            getContent()
            if (hasContent) {
                showHintDialog()
                return@setOnClickListener
            }
            finish()

        }
        mBinding.onClick = this
        mBinding.itvType.setOnWholeItemClickListener(this)
        mBinding.itvArea.setOnWholeItemClickListener(this)
        mBinding.itvArea.setContentTextEnd()
        mBinding.itvPhone.setInfilterType(ItemInputTextView.TYPE_PHONE)
        mBinding.itvMoney.setInfilterType(ItemInputTextView.TYPE_NUMBER_DECIMAL)
        mBinding.itvMoney.setCheck(10, 2, false)
        mBinding.itvMoney.setLabelRightMargin()
        initData()


    }

    private fun initData() {
        if(!TextUtils.isEmpty(no)){
            mViewModel.getInfo(no)
            map["no"]=no
            isPublish=false
        }else{
            mData=DemandDetailEntity()
        }
        mViewModel.ldUrl.observe(this, { url: String? ->
            map["fileName"] = fileName
            map["fileUrl"] = url
            mViewModel.getFileInfo(url)

        })
        mViewModel.ldType.observe(this, {
            mType.addAll(it)
            initTypePicker()
        })
        mViewModel.ldFileInfo.observe(this,{

            map["fileInfo"] = it
            mViewModel.edit(map)

        })
        mViewModel.ldResult.observe(this, {
            if (it) {

                //刷新详情页
                EventBus.getDefault().post(
                    MainEvent.make().setMessageTag(EventConstant.EVEN_MERCHANT_SELF_REFRESH_DEMANDS_DETAIL)
                )
                if (isPublish) {
                    MToast.showToast(this, "发布成功")
                } else {
                    MToast.showToast(this, "编辑成功")
                }
                if(isSelf){
                    ARouter.getInstance().build(PathMerchant.SelfDemandListActivity).navigation()
                }else{
                    //刷新列表页
                    EventBus.getDefault()
                        .post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH_DEMANDS))
                }
                finish()
            }
        })
        mViewModel.ldInfo.observe(this,{
            mData=it
            mBinding.itvName.content=mData?.demandName
            mBinding.itvMoney.content=mData?.demandMoney
            mBinding.itvPhone.content=mData?.linkPhone
            mBinding.itvPerson.content=mData?.linkName
            mBinding.itvType.content=mData?.demandTypeName
            map["demandTypeNo"]=mData?.demandTypeNo
            mBinding.itvArea.content=mData?.cityStr
            mBinding.etDesc.editContent=mData?.demandInfo
            setFileInfo()
            if(mData?.cityInfos!=null) {
                for (data in mData?.cityInfos!!) {
                    var city: BaseAreaEntity<*> = BaseAreaEntity<Any?>()
                    city.name=data.proviceName
                    city.id=data.proviceCode.toString()
                    cityList.add(city)
                }
            }
        })

    }
    private fun setFileInfo() {
        if (mData?.fileName != null && mData?.fileName != "") {
            mBinding.rlAnnexInfo.visibility = View.VISIBLE
            mBinding.tvUploadAnnex.visibility = View.GONE
            GlobalScope.launch(Dispatchers.IO) {
                var size:String=FileUtil.getFileSize(mData?.fileUrl)
                GlobalScope.launch(Dispatchers.Main) {
                    mBinding.tvAnnexSize.text=size
                }
            }
           var fileName:String= mData?.fileName!!
            mBinding.tvAnnexName.text = mData?.fileName
            if (fileName.endsWith(FILE_TYPE_RAR) || fileName.endsWith(
                    FILE_TYPE_ZIP
                )
            ) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_zip)
            } else if (fileName.endsWith(FILE_TYPE_DOC) || fileName.endsWith(
                    FILE_TYPE_DOCX
                )
            ) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_doc)
            } else if (fileName.endsWith(FILE_TYPE_PPT) || fileName.endsWith(
                    FILE_TYPE_PPTX
                )
            ) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_ppt)
            } else if (fileName.endsWith(FILE_TYPE_XLS) || fileName.endsWith(
                    FILE_TYPE_XLSX
                )
            ) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_xlsx)
            } else if (fileName.endsWith(FILE_TYPE_PDF)) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_pdf)
            } else if (fileName.endsWith(FILE_TYPE_JPG) || fileName.endsWith(
                    FILE_TYPE_JPEG
                ) || fileName.endsWith(FILE_TYPE_PNG)
            ) {
                mBinding.ivAnnexSimple.setImageResource(R.mipmap.merchant_icon_img_type)
            }
           
        }
    }

    private fun initTypePicker() {
        mTypePicker =
            PickerHelper.with(this).getCommonPicker(mType, object : OnOptionsSelectListener {
                override fun onOptionsSelect(
                    options1: Int,
                    options2: Int,
                    options3: Int,
                    v: View?
                ) {
                    var data: DemandType = mType[options1]
                    mBinding.itvType.content = data.demandTypeName
                    map["demandTypeNo"]=data.no.toLong()

                }
            })
        mTypePicker.setTitleText("选择所属类型")
        mTypePicker.show()
    }

    fun getContent() {
        strTitle = mBinding.itvName.content
        strType = mBinding.itvType.content
        strArea = mBinding.itvArea.content
        strLinkPhone = mBinding.itvPhone.content
        strLinkName = mBinding.itvPerson.content
        strDesc = mBinding.etDesc.editContent
        strMoney = mBinding.itvMoney.content
        hasContent =
            (!TextUtils.isEmpty(strTitle) || !TextUtils.isEmpty(strArea) || !TextUtils.isEmpty(strType) ||
                    !TextUtils.isEmpty(strLinkPhone) || !TextUtils.isEmpty(strMoney) || !TextUtils.isEmpty(
                strLinkName
            ) || !TextUtils.isEmpty(strDesc)
                    || !TextUtils.isEmpty(fileName))
    }

    //温馨提示
    private fun showHintDialog() {
        RoundDialog.Builder(this)
            .title("温馨提示")
            .content("当前操作会丢失已填写的信息，确定是否继续？")
            .cancel("取消")
            .confirm("确定")
            .cancelable(false)
            .confirmCallback { finish() }.show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_commit -> {
                if (ClickUtils.isDoubleClick()) {
                    return
                }
                getContent()
                if (TextUtils.isEmpty(strTitle)) {
                    MToast.showToast(this, "请输入标题")
                    return
                }
                if (TextUtils.isEmpty(strType)) {
                    MToast.showToast(this, "请选择所属类型")
                    return
                }
                if (TextUtils.isEmpty(strMoney)) {
                    MToast.showToast(this, "请输入预算价格")
                    return
                }
                if (TextUtils.isEmpty(strArea)) {
                    MToast.showToast(this, "请选择地区要求")
                    return
                }
                if (TextUtils.isEmpty(strLinkName)) {
                    MToast.showToast(this, "请输入联系人")
                    return
                }
                if (TextUtils.isEmpty(strLinkPhone)) {
                    MToast.showToast(this, "请输入联系电话")
                    return
                } else if (!CheckUtils.isMobileForService(strLinkPhone)) {
                    MToast.showToast(this, "输入正确的电话格式！")
                    return
                }
                if (TextUtils.isEmpty(strDesc)) {
                    MToast.showToast(this, "请输入需求描述")
                    return
                }
                DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false)

                map["linkName"]=strLinkName
                map["linkPhone"]=strLinkPhone
                map["demandMoney"]=strMoney
                map["demandName"]=strTitle
                map["demandInfo"]=strDesc

                if (!TextUtils.isEmpty(fileName)) {
                    mViewModel.uploadFile(File(filePath))
                } else {
                    mViewModel.edit(map)

                }
            }
            R.id.tv_annex_delete -> {
                if (!ClickUtils.isDoubleClick()) {
                    fileName = ""
                    fileSize = ""
                    fileType = ""
                    mBinding.tvUploadAnnex.visibility = View.VISIBLE
                    mBinding.rlAnnexInfo.visibility = View.GONE
                    map["fileName"] = ""
                    map["fileUrl"] = ""
                    map["fileInfo"] = "{}"
                }
            }
            R.id.tv_upload_annex -> {
                if (!ClickUtils.isDoubleClick()) {
                    val fileIntent = Intent(Intent.ACTION_GET_CONTENT)
                    fileIntent.addCategory(Intent.CATEGORY_OPENABLE)
                    //设置类型
                    fileIntent.type =
                        "application/zip|image/png|application/pdf|application/rar|image/jpeg"
                    //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        fileIntent.putExtra(
                            Intent.EXTRA_MIME_TYPES,
                            arrayOf(
                                "application/zip",
                                "image/png",
                                "application/pdf",
                                "application/rar",
                                "image/jpeg"
                            )
                        )
                    }
                    startActivityForResult(
                        fileIntent,
                        OPEN_FILE
                    )
                }
            }


        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == OPEN_FILE) { //选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null")
                    return
                }
                handleFileChoose(data)
            } else if (requestCode == SELECT_CITY) {
                cityList = data?.getSerializableExtra("cityList") as MutableList<BaseAreaEntity<*>>
                var strArea = StringBuffer()
                var selectList= mutableListOf<DemandInfoEntity.CityIdsBean>()
                for (num in cityList.indices) {
                    var cityInfo:DemandInfoEntity.CityIdsBean =DemandInfoEntity.CityIdsBean()
                    var city: BaseAreaEntity<*> =cityList[num]
                    strArea.append(city.name)
                    if (num != cityList.size - 1) {
                        strArea.append("/")
                    }
                    if(TextUtils.isEmpty(city.parentId)) {
                        cityInfo.parentId=city.id.toInt()
                        cityInfo.id=city.id.toInt()
                        cityInfo.ids= mutableListOf()
                        if(city.name!="全国"){
                            cityInfo.ids.add(99999)
                            cityInfo.id=99999
                        }else{
                            cityInfo.ids.add(city.id.toInt())
                        }
                    }else{
                        cityInfo.parentId=city.parentId.toInt()
                        cityInfo.ids= mutableListOf()
                        cityInfo.ids.add(city.id.toInt())
                        cityInfo.id=city.id.toInt()

                    }
                    selectList.add(cityInfo)
                }

                map["cityIds"]=selectList
                mBinding.itvArea.content = strArea.toString()
            }
        }
    }

    private fun handleFileChoose(data: Intent) {
        val uri = data.data
        /**
         * 得到uri对路径
         */
        if ("content".equals(uri.scheme, ignoreCase = true) || "file".equals(
                uri.scheme,
                ignoreCase = true
            )
        ) {
            filePath = FileUtil.getFilePathForN(this, uri)
            fileName = File(filePath).name
            val extension = FileUtil.getExtensionName(fileName)
            if (TextUtils.isEmpty(extension)) {
                MToast.showToast(this, "未获取到文件格式")
                return
            }
            if (extension != "pptx" && extension != "ppt" && extension != "pdf"
                && extension != "png" && extension != "jpg" && extension != "jpeg"
                && extension != "xls" && extension != "xlsx" && extension != "doc"
                && extension != "docx"
            ) {
                MToast.showToast(this, "上传附件格式不正确！")
                return
            }
            if (checkFileSize(filePath)) {
                mBinding.tvUploadAnnex.visibility = View.GONE
                mBinding.rlAnnexInfo.visibility = View.VISIBLE
                val fileLength = FileUtil.getFileLength(filePath)
                fileSize = FileUtil.formatFileSize(fileLength)
                fileType = FileUtil.getMimeType(File(filePath))
                mBinding.tvAnnexName.text = fileName
                mBinding.tvAnnexSize.text = fileSize
                setImageIcon()
            }
            return
        }
        /***
         * //4.4以后
         */
        filePath = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            FileUtils.getPath(this, uri)
        } else { //4.4以下下系统调用方法
            FileUtil.getRealPathFromURI(uri, this)
        }
        if (TextUtils.isEmpty(filePath)) {
            MToast.showToast(this, "未找到文件路径")
            return
        }
        fileName = File(filePath).name
        val extension = FileUtil.getExtensionName(fileName)
        if (TextUtils.isEmpty(extension)) {
            MToast.showToast(this, "未获取到文件格式")
            return
        }
        if (extension != "pptx" && extension != "ppt" && extension != "pdf"
            && extension != "png" && extension != "jpg" && extension != "jpeg"
            && extension != "xls" && extension != "xlsx" && extension != "doc"
            && extension != "docx"
        ) {
            MToast.showToast(this, "上传附件格式不正确！")
            return
        }
        if (checkFileSize(filePath)) {
            mBinding.tvUploadAnnex.visibility = View.GONE
            mBinding.rlAnnexInfo.visibility = View.VISIBLE
            val fileLength = FileUtil.getFileLength(filePath)
            fileSize = FileUtil.formatFileSize(fileLength)
            fileType = FileUtil.getMimeType(File(filePath))
            mBinding.tvAnnexName.setText(fileName)
            mBinding.tvAnnexSize.text = fileSize
            setImageIcon()
        }
        LogUtil.d("TAG", "handleFileChoose filePath:$filePath")
    }

    private fun setImageIcon() {
        when (fileType) {
            "image/jpg", "image/png", "image/jpeg" -> Glide.with(this)
                .load(R.mipmap.merchant_icon_img_type).into(mBinding.ivAnnexSimple)
            "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> Glide.with(
                this
            ).load(R.mipmap.merchant_icon_doc).into(mBinding.ivAnnexSimple)
            "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation" -> Glide.with(
                this
            ).load(R.mipmap.merchant_icon_ppt).into(mBinding.ivAnnexSimple)
            "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> Glide.with(
                this
            ).load(R.mipmap.merchant_icon_xlsx).into(mBinding.ivAnnexSimple)
            "application/pdf" -> Glide.with(this).load(R.mipmap.merchant_icon_pdf)
                .into(mBinding.ivAnnexSimple)
        }
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private fun checkFileSize(filePath: String): Boolean {
        var sizeCount = 0f
        val fileLength = FileUtil.getFileLength(filePath)
        val fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB)
        if (fileSize.contains("MB")) {
            val fileSizeCount = fileSize.replace("MB", "")
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = fileSizeCount.toFloat()
                if (sizeCount > 10) {
                    MToast.showToast(this, "请上传10MB内的文件！")
                    return false
                }
            }
        }
        return true
    }

    override fun OnWholeItemClick(view: View?) {
        when (view?.id) {
            R.id.itv_type -> {
                if (mViewModel.ldType.value == null) {
                    mViewModel.getType()
                }else {
                    mTypePicker.setTitleText("选择所属类型")
                    mTypePicker.show()
                }

            }
            R.id.itv_area -> {
                ARouter.getInstance().build(PathMerchant.SelectCityActivity).withSerializable(
                    RouterKey.DATA, cityList as Serializable
                ).navigation(
                    this,
                    SELECT_CITY
                )

            }

        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getContent()
            if (hasContent) {
                showHintDialog()
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

}